package com.pinyougou.solrutil;

import com.alibaba.fastjson.JSON;
import com.pinyougou.mapper.TbItemMapper;
import com.pinyougou.pojo.TbItem;
import com.pinyougou.pojo.TbItemExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class SolrUtil {

    @Autowired
    private TbItemMapper itemMapper;

    @Autowired
    private SolrTemplate solrTemplate;

    public void importItemData() {

        TbItemExample tbItemExample = new TbItemExample();

        tbItemExample.createCriteria().andStatusEqualTo("1");


        List<TbItem> list = itemMapper.selectByExample(tbItemExample);

        for (TbItem tbItem : list) {
            //将json类型的规格转换为集合
            Map map = JSON.parseObject(tbItem.getSpec());

            tbItem.setSpecMap(map);

            System.out.println(tbItemExample);

        }

        solrTemplate.saveBeans(list);

        solrTemplate.commit();

    }

    //main方法做初始导入操作
    public static void main(String[] args) {

        //加载配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath*:spring/applicationContext*.xml");

        //通过获取到的上下文对象从ioc容器中取到对象
        SolrUtil solrUtil = (SolrUtil) applicationContext.getBean("solrUtil");

        solrUtil.importItemData();

    }

}
